<?php

namespace NorthernLights\JetBrainsLicensing;

use NorthernLights\JetBrainsLicensing\Exception\PrivateKeyFileException;

/**
 * Class PrivateKeyFile
 * @package NorthernLights\JetBrainsLicensing
 */
class PrivateKeyFile
{
    /** @var  string */
    private $pemFilename;

    /** @var string|null */
    private $pemPassword;

    /**
     * CertFile constructor.
     *
     * @param string $certFilename
     * @param null $certPassword
     *
     * @throws PrivateKeyFileException
     */
    public function __construct($pemFilename, $pemPassword = null)
    {
        if ($pemFilename === '' || $pemFilename === null) {
            throw new PrivateKeyFileException('PEM filename might not be empty');
        }

        $this->validateFile($pemFilename);

        $this->pemPassword = $pemPassword;
    }


    /**
     * If instance is treated as a string, dump file contents
     *
     * @return string
     */
    public function __toString()
    {
        $contents = file_get_contents($this->pemFilename);

        return (is_string($contents) ? $contents : '');
    }

    /**
     * @return string
     */
    public function getFilename()
    {
        return $this->pemFilename;
    }

    /**
     * @return string|null
     */
    public function getPassword()
    {
        return $this->pemPassword;
    }

    /**
     * Check if file is of valid type, and if true, assign to property
     *
     * @param string $filename
     *
     * @throws PrivateKeyFileException
     */
    private function validateFile($filename)
    {
        $fileInfo = new \SplFileInfo($filename);

        if (! $fileInfo->isReadable()) {
            throw new PrivateKeyFileException('Certificate file either doesn\'t exist or permissions are inadequate');
        }

        //in some VPSs and virtual hosts, the mime_content_type function is not working properly.
        //Consider replacing it with https://github.com/dfridrich/PhpMimeType in future
        $fileMimeType = 'text/plain';
        if (function_exists ('mime_content_type')) {
            $fileMimeType = mime_content_type($filename);
        }

        if ($fileMimeType !== 'text/plain') {
            throw new PrivateKeyFileException(
                sprintf(
                    'Supplied PEM file is expected to be of mime type "text/plain", "%s" given',
                    $fileMimeType
                )
            );
        }

        if ($fileInfo->getSize() < 128) {
            throw new PrivateKeyFileException('PEM file may not be smaller than 128 bytes');
        }

        if ($fileInfo->getSize() > 8192) {
            throw new PrivateKeyFileException('PEM file may not be larger than 8192 bytes');
        }

        $this->pemFilename = $filename;
    }
}
